package com.example.demo.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.example.demo.constant.RedisConstant;
import com.example.demo.controller.bean.Result;
import com.example.demo.mapper.SysRoleMapper;
import com.example.demo.mapper.entity.SysMenu;
import com.example.demo.mapper.entity.SysRole;
import com.example.demo.service.SysMenuService;
import com.example.demo.service.SysRoleService;
import com.example.demo.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Lucy
 * @create 2024-02-03 20:56
 */
@RequestMapping("menuController")
@Api(value = "菜单管理", tags = {"菜单管理"})
@Slf4j
@RestController
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private RedisUtil redisUtil;

    @ResponseBody
    @ApiOperation("侧边栏动态获取菜单")
    @RequestMapping(value = "asideMenus", method = {RequestMethod.POST,  RequestMethod.GET})
    public Result<List<SysMenu>> asideMenus() {
        int userId = StpUtil.getLoginIdAsInt();
        //获取用户的权限（既角色信息）
        SysRole role = sysRoleService.getRoleByUserId(userId);
        //角色权限
        int roleId = role.getRoleId();
        List<SysMenu> menus = null;
        //查询缓存是否存在
        String key = RedisConstant.getList_Menu_aside;
        if (redisUtil.hasKey(key + ":" + roleId)) {
            //缓存存在
            menus = (List<SysMenu>) redisUtil.get(key + ":" + role.getRoleId());
        } else {
            //缓存不存在
            List<Integer> menuId = sysMenuService.findMenuIdBySysRoleId(roleId);
            menus = sysMenuService.buildMenuList(null);
            if(menus != null && menus.size() > 1){
                menus = menus.stream().filter(menu -> menuId.contains(menu.getMenuId())).collect(Collectors.toList());
                if(menus.size() <= 0) return Result.fail("获取侧边菜单栏错误");
            }else{
                return Result.fail("获取侧边菜单栏错误");
            }
            long time = RedisConstant.getList_Menu_aside_Time;
            redisUtil.set(key + ":" + roleId, menus, time);
        }
        return Result.ok("ok",menus);
    }
}
